package com.snts.synchronization.protocol.adapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import javax.naming.OperationNotSupportedException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;

import nu.xom.Document;
import nu.xom.Element;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import com.snts.synchronization.core.AuthRequest;
import com.snts.synchronization.garbage.Utils;
import com.snts.synchronization.protocol.ProtocolAdapter;

public class AuthRequestPA extends BaseXMLProtocolAdapter<AuthRequest> {

	private static final Log log = LogFactory.getLog(AuthRequestPA.class);
	
	private AuthRequest authRequest = new AuthRequest();
	
	@Override
	protected AuthRequest popMessage() {
		AuthRequest message = authRequest;
		authRequest = new AuthRequest();
		return message;
	}

	@Override
	protected Element getMessageXOM(AuthRequest message) {
		Element root = new Element("auth-request");
		Element el = new Element("username");
		el.appendChild(message.getUserName());
		root.appendChild(el);
		el = new Element("password");
		el.appendChild(message.getPassword());
		root.appendChild(el);
		return root;
	}

	@Override
	protected void doEndElement(String uri, String localName, String qName, String textValue) throws SAXException {
		if("username".equals(qName)){
			authRequest.setUserName(stringBuffer.toString());
		} else if("password".equals(qName)){
			authRequest.setPassword(stringBuffer.toString());
		}
	}
	
	public static void main(String[] args) throws Exception {

		String str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
				     + "<auth-request><username>isk<andar</username><password>123</password></auth-request>";
		
		Element ar = new Element("auth-request");
		Element un = new Element("username");
		un.appendChild("iska<n&dar");
		ar.appendChild(un);
		Element pwd = new Element("password");
		pwd.appendChild("qwerty");
		ar.appendChild(pwd);
		
		Document doc = new Document(ar);
		
		System.out.println(ar.toXML());
		
		AuthRequestPA authRequestPA = new AuthRequestPA();
		AuthRequest ar1 = authRequestPA.parseMessage(new ByteArrayInputStream(doc.toXML().getBytes(Charset.forName("UTF-8"))));
		System.out.println(ar1.getUserName());
		System.out.println(ar1.getPassword());
		
	}

}
